<?php 

	require_once __DIR__."/../Models/user.php";

	use Symfony\Component\HttpFoundation\Request;
	use Symfony\Component\HttpFoundation\Response;

	$user_model = new Models\User($app);
	$user = $app['controllers_factory'];

	class Responce
	{
		public $page = 1;
		public $total = 0;
		public $records;
		public $rows = array();
	}
	
	$responce = new Responce();

	$user->get('/', function(Request $request) use ($app, $user_model, $responce){
	//	$page = $request->get('page');
	//	$limit = $request->get('rows');
	//	$sidx = $request->get('sidx');
	//	$sord = $request->get('sord');


		$page = 1;
		$total = 1;
		$limit = 10;	

		$count = $user_model->getCount();

		if($count > 0){
			$total_pages = ceil($count/$limit);
		} else {
			$total_pages = 0;
		}

		if($page > $total_pages) $page = $total_pages;

		$start = $limit*$page - $limit;
		$res = $user_model->getAll();
		//$res = $user_model->getAll($sord, $sidx, $start, $limit);

		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records = $count;
		$i = 0;	
		foreach ($res as $val) {
			$responce->rows[$i]['id'] = $val['user_id'];
			$responce->rows[$i]['cell'] = $val;
			$i++;
		}

		return json_encode($responce);

	})->bind('users');
	
	$user->post('/', function(Request $request) use ($app, $user_model, $responce){
		$data = array(
			"user_id"=>$request->get('id'), 
			"user_login"=>$request->get('user_login'), 
			"user_pass"=>$request->get('user_pass'),

		);

		$oper = $request->get('oper');
		

		if($oper == 'add'){
			$res = $user_model->inser($data);	
		}elseif($oper == 'edit'){
			$res = $user_model->update($data);
		}elseif($oper == 'del'){
			$res = $user_model->delete($data);
		}

		/*$i = 0;	
		foreach ($res as $val) {
			$responce->rows[$i]['id'] = $val['user_id'];
			$responce->rows[$i]['cell'] = $val;
			$i++;
		}
		return json_encode($responce);
		*/
		return "";
	});


	/*
	$user->post('/', function(Request $request) use ($app, $user_model){
		$data = array(
			"user_login"=>"login", 
			"user_pass"=>"pass"
		);
		echo json_encode( $data );
		$res = $user_model->insert($data);
		return json_encode($res);
	});

	*/

	$user->get('/{id}' , function($id) use($app, $user_model){
		$res = $user_model->getOne((int) $id);
		return json_encode($res);
	});

	$user->put('/{id}' , function($id, Request $request) use($app, $user_model){
		$res = $user_model->update((int) $id);
		return json_encode($res);
	});
	$user->delete('/{id}' , function($id) use($app, $user_model){
		$res = $user_model->delete((int) $id);
		return json_encode($res);
	});

	return $user;

?>